import React, { } from 'react'
import F2Chart from './chart'
import { PieProps } from './type'
import { randomId } from './util'

function draw(chart: any, F2: any, props: PieProps): void {
  if (!chart) {
    return
  }

  const { series, legend, style, radius, innerRadius, tooltip, guide, cascade, pieLabel, sidePadding, activeShape } = props

  chart.clear()

  if (!Array.isArray(series) || series.length <= 0) {
    return
  }

  const data = cascade ? series : series.map(item => {
    item.key = 'key'
    return item
  })
  chart.source(data)
  chart.coord('polar', {
    transposed: true,
    innerRadius,
    radius: radius || 1
  })

  if (pieLabel && chart.pieLabel) {
    // 添加饼图文本
    chart.pieLabel({
      sidePadding,
      activeShape,
      label1: function label1(label, color) {
        return {
          text: label.type,
          fill: color
        }
      },
      label2: function label2(label, color) {
        return {
          text: label.data,
          fill: color,
          fontWeight: 'bold'
        }
      }
    })
  }

  const color: string[] = []
  const dftColors = F2.Global.colors
  const length = dftColors.length
  series.forEach((kind, i) => {
    color.push(kind.color || dftColors[i % length])
  })
  chart.axis(false)
  chart.tooltip(tooltip)
  chart.legend(legend)

  chart.interval()
    .position('key*data')
    .color('type', color)
    .adjust('stack')
    .style(style)

  if (guide) {
    if (guide.text) {
      chart.guide().text(guide.text)
    }
  }

  chart.render()
}

type OwnProps = PieProps

const defaultProps: OwnProps = {
  cn: 'pie',
  series: [],
  radius: 1,
  innerRadius: 0,
  cascade: false,
  pieLabel: false,
  sidePadding: 40,
  tooltip: false,
  legend: false
}

const onInitChart = (F2, config, props) => {
  const chart = new F2.Chart(config);
  console.log('Pie onInitChart')
  draw(chart, F2, props)
  // 注意：需要把chart return 出来
  return chart;
}

export default function Pie(props: OwnProps = defaultProps) {
  return (
    <F2Chart id={`pie_${randomId()}`} onInit={(f, conf) => onInitChart(f, conf, props)} data={props}></F2Chart>
  )
}

Pie.defaultProps = defaultProps
